package com.lavida.common.utils;

import java.lang.management.ManagementFactory;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.lavida.project.system.emp.domain.Emp;
import com.lavida.project.system.emp.mapper.EmpMapper;

/**
 * 时间工具类
 * 
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{	
	
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    
    public static String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    
    private static final int[] LEAPMONTHSDAYS=new int[] {31,29,31,30,31,30,31,31,30,31,30,31};
	private static final int[] COMMONMONTHSDAYS=new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    public String paress(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String timeFormat = sdf.format(date);
        return timeFormat;
    }
    public static Date parseDates(String str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {	 Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str); 
        	 return date;
        	
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    /**
     * 获取传来日期的月
     * @param str
     * @return
     */
    public static int dateMonth(Date date)
    {
    	 Calendar a = Calendar.getInstance();
    	 a.setTime(date);
         int month = a.get(Calendar.MONTH)+1;
             System.out.println(month);
             return month;
    }
    /**
     *  获取传来日期的年
     * @param str
     * @return
     */
    public static int dateYear(Date date)
    {
    	 Calendar a = Calendar.getInstance();
         	a.setTime(date);
             int year = a.get(Calendar.YEAR);
             System.out.println(year+"");
             return year;
    }
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
    
    
    /**
     * date2比date1多的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
 
 
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) // 不同年
        {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) // 闰年
                {
                    timeDistance += 366;
                } else // 不是闰年
                {
                    timeDistance += 365;
                }
            }
 
 
            return timeDistance + (day2 - day1);
        } else // 同一年
        {
            System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }
    /**
     * 判断两个日期之间是否刚好相差了N月，多出天数为0的情况
     * @param date1
     * @param date2
     * @return
     */
    public static int differentMonths(Date date1, Date date2) {
    	int result = 0;
    	boolean resultFlag = false;
    	Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
 
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        
        int month1 = cal1.get(Calendar.MONTH);
        int month2 = cal2.get(Calendar.MONTH);
        
        int day1 = cal1.get(Calendar.DAY_OF_MONTH);
        int day2 = cal2.get(Calendar.DAY_OF_MONTH);
        
        if(day1==day2) {
        	resultFlag = true;
        	result = (year2-year1)*12+(month2 - month1);
        }else {
        	while(date1.before(date2)) {
        		year1 = cal1.get(Calendar.YEAR);
        		if (year1 % 4 == 0 && year1 % 100 != 0 || year1 % 400 == 0) {
        			date1 = addDays(date1, LEAPMONTHSDAYS[month1]);
        		}else {
        			date1 = addDays(date1, COMMONMONTHSDAYS[month1]);
        		}
        		cal1.setTime(date1);
        		System.out.println(parseDateToStr(YYYY_MM_DD, date1));
        		
        		if(isSameDay(date1, date2)) {
        			result++;
        			resultFlag = true;
        			break;
        		}
        		if(date1.before(date2)) {
            		result++;
        		}
        		month1++;
        		if(month1==12) {
        			month1=0;
        		}
        	}
        }
        System.out.println(result);
        if(!resultFlag) {
        	result = 0;
        }
        
        
        return result;
    }
    /**

     * 获取两个日期相差的月数

     */

    public static int getMonthDiff(Date d1, Date d2) {
    	if (d1==null) {
			return 0;
		}
    	Calendar c1 = Calendar.getInstance();

    	Calendar c2 = Calendar.getInstance();

    	c1.setTime(d1);

		c2.setTime(d2);
		int year1 = c1.get(Calendar.YEAR);
		
		int year2 = c2.get(Calendar.YEAR);
		
		int month1 = c1.get(Calendar.MONTH);
		
		int month2 = c2.get(Calendar.MONTH);
		
		int day1 = c1.get(Calendar.DAY_OF_MONTH);
		
		int day2 = c2.get(Calendar.DAY_OF_MONTH);
		
		// 获取年的差值 
		
		int yearInterval = year1 - year2;
		
		// 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
		
		if (month1 < month2 || month1 == month2 && day1 < day2)
		
		yearInterval--;
		
		// 获取月数差值
		
		int monthInterval = (month1 + 12) - month2;
		
		if (day1 < day2)
		
		monthInterval--;
		
		monthInterval %= 12;
		int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
		
		return monthsDiff;

    }
    //计算入职时间(本年时间)到本时间年底相差的天数
    public static int daysreview(Date sendDate) {
    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         try {
             sendDate = sdf.parse(sdf.format(sendDate));
         } catch (Exception e) {
             e.printStackTrace();
         }
         Calendar news = Calendar.getInstance();
         news.setTime(new Date());
         Calendar cal1 = Calendar.getInstance();
         cal1.setTime(sendDate);
         int year1 = news.get(Calendar.YEAR);
         String datee = year1 + "-12-31";
         System.out.println("今年年底："+year1);
         cal1.set(news.get(Calendar.YEAR),cal1.get(Calendar.MONTH),cal1.get(Calendar.MONDAY));
        
         //入职日期(本年)
         sendDate = cal1.getTime();
         System.out.println("入职本年:"+sendDate);
         //本年年底日期
         Date startDate = DateUtils.parseDate(datee);	
         return differentDays(sendDate,startDate);
        /* return daysBetween(sendDate,startDate);*/
    }
    public static int dayreiv(Date date) {
    	int year = 0; 
    	if(date==null) {
    		year = 0;
    	}else {
    		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	        Calendar bef = Calendar.getInstance();
    	        Calendar aft = Calendar.getInstance();
    	        bef.setTime(date);
    	        aft.setTime(new Date());
    	        year = aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR);
    	        System.out.println("相差年份：" + (year));
    	}
        return year;
    }
    public static int daysBetween(Date sendDate, Date startDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            sendDate = sdf.parse(sdf.format(sendDate));
            startDate = sdf.parse(sdf.format(startDate));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(sendDate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(startDate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }
    /**
     * 判断两个日期之间相差的月份数
     * @param date1
     * @param date2
     * @return
     */
    public static int differentMonths2(Date date1, Date date2) {
    	if (date1==null) {
			return 0;
		}
    	int result = 0;
    	Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
 
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        
        int month1 = cal1.get(Calendar.MONTH);
        int month2 = cal2.get(Calendar.MONTH);
        
        int day1 = cal1.get(Calendar.DAY_OF_MONTH);
        int day2 = cal2.get(Calendar.DAY_OF_MONTH);
        
        if(day1==day2) {
        	result = (year2-year1)*12+(month2 - month1);
        }else {
        	while(date1.before(date2)) {
        		year1 = cal1.get(Calendar.YEAR);
        		if (year1 % 4 == 0 && year1 % 100 != 0 || year1 % 400 == 0) {
        			date1 = addDays(date1, LEAPMONTHSDAYS[month1]);
        		}else {
        			date1 = addDays(date1, COMMONMONTHSDAYS[month1]);
        		}
        		cal1.setTime(date1);
//        		System.out.println(parseDateToStr(YYYY_MM_DD, date1));
        		
        		if(isSameDay(date1, date2)) {
        			result++;
        			break;
        		}
        		if(date1.before(date2)) {
            		result++;
        		}
        		month1++;
        		if(month1==12) {
        			month1=0;
        		}
        		
        	}
        }
        
        	result = 0;
        return result;
    }
    
    
    /**
     * date2比date1多的月份
     *
     * @param date1
     * @param date2
     * @return
     */
    /*public static int differentMonths(Date date1, Date date2) {
        Calendar bef = Calendar.getInstance();
        bef.setTime(date1);
        Calendar aft = Calendar.getInstance();
        aft.setTime(date2);
        
        int surplus = aft.get(Calendar.DATE) - bef.get(Calendar.DATE);
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        System.out.println(surplus);
        if(surplus<0) {
        	
        }
        surplus = surplus <= 0 ? 1 : 0;
        System.out.println(surplus);
        return Math.abs(month + result) + surplus;
    }*/
    
    
    
   /* public static int dayComparePrecise(Date fromDate,Date toDate){
    	Calendar  from  =  Calendar.getInstance();
        from.setTime(fromDate);
        Calendar  to  =  Calendar.getInstance();
        to.setTime(toDate);
        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);
        int fromDay = from.get(Calendar.DAY_OF_MONTH);
        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);
        int toDay = to.get(Calendar.DAY_OF_MONTH);
        int year = toYear  -  fromYear;
        int month = toMonth  - fromMonth;
        int day = toDay  - fromDay;
        System.out.println("相差年："+year+",相差月："+month+",相差天："+day);
        return day;
    }*/
    /**
     * 
     * @param startDay
     * @param endDay
     * @param stype 0为多少天，1为多少个月，2为多少年
     * @return
     */
   /* public static int compareDate(Date fromDate,Date toDate,int stype){
    	int n = 0; 
    	String[] u = {"天","月","年"};
    	String formatStyle = stype==1?"yyyy-MM":"yyyy-MM-dd";
    	Calendar  from  =  Calendar.getInstance();
    	from.setTime(fromDate);
    	Calendar  to  =  Calendar.getInstance();
    	to.setTime(toDate);
    	 while (!from.after(to)) {
    		 n++;
    		 if(stype==1){ 
    			 from.add(Calendar.MONTH, 1);          // 比较月份，月份+1 
             } else{ 
            	 from.add(Calendar.DATE, 1);           // 比较天数，日期+1 
             } 
    	 }
    	 n = n-1; 
         if(stype==2){ 
             n = (int)n/365; 
         }
         System.out.println(" 相差多少"+u[stype]+":"+n);       
    	return n;
    }*/
    
    /**
     * 获取当月天数
     * @param date
     * @return
     */
    public static Integer getMonthDays(String date) {
        Calendar a = Calendar.getInstance();
        a.setTime(dateTime("yyyy-MM-dd",date));
        //把日期设置为当月第一天
        a.set(Calendar.DATE, 1);
        //日期回滚一天，也就是最后一天
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }
    
    public static String getMonthStartStringDateByMonth(String date, String dateFormat) {
    	Calendar c = Calendar.getInstance();
    	c.setTime(dateTime(dateFormat,date));
    	c.add(Calendar.MONTH, 0);  
    	c.set(Calendar.DAY_OF_MONTH, 1);  
    	return DateUtils.parseDateToStr(YYYY_MM_DD, c.getTime());
    }
    
    /**
     * 获取月末日期
     * @param date
     * @param dateFormat
     * @return
     */
    public static String getMonthEndStringDateByMonth(String date, String dateFormat) {
        Calendar c = Calendar.getInstance();
        c.setTime(dateTime(dateFormat,date));
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        return DateUtils.parseDateToStr(YYYY_MM_DD, c.getTime());
    }
    /**
     * 	距离生日还有多少天
     * @param birthday
     * @return
     */
	public static Integer getBirthDayes(Date birthday) {
		System.out.println(birthday);
		Integer days = 0;
		if (birthday==null) {
			days = null;
		}else {
			// TODO Auto-generated method stub
				String ps = DateUtils.parseDateToStr("yyyy-MM-dd",birthday);
				System.out.println(ps.toString());
				Calendar cToday = Calendar.getInstance(); // 存今天
				Calendar cBirth = Calendar.getInstance(); // 存生日
				cBirth.setTime(birthday); // 设置生日
				cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR)); // 修改为本年
				if (cBirth.get(Calendar.DAY_OF_YEAR) < cToday.get(Calendar.DAY_OF_YEAR)) {
					// 生日已经过了，要算明年的了
					days = cToday.getActualMaximum(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
					days += cBirth.get(Calendar.DAY_OF_YEAR);
				} else {
					// 生日还没过
					days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
				}
		}
		return days;
	}
	public static void main(String[] args) {
		
		getBirthDayes(new Date());
	}
    
}
